import React, {Component} from "react";
import {
	View,
	Text,
	ScrollView,
	StyleSheet,
	Keyboard,
} from "react-native";
import {observer} from "mobx-react/native";
import { List, InputItem, Toast, Button } from 'antd-mobile';

import User from "../models/User";

@observer
class Login extends Component {
	static navigationOptions = {
		title: "登录",
	}
	constructor(props) {
		super(props);
		this.state = {
			hasError: false,
			value: '',
			pwd: '',
			btnBg: "#e1e1e1",
			btnColor: "#525252",
		}
	}
	//手机号输入错误提示
	onErrorClick = () => {
		if(this.state.hasError) {
			Toast.info("请输入11位有效数字")
		}
	}
	//用户输入时对手机号码进行验证
	onPhoneChange = (value) => {
		if(value.replace(/\s/g, '').length < 11) {
			this.setState({
				hasError: true,
			});
		}else {
			this.setState({
				hasError: false,
			});
			if(this.state.pwd) {
				this.setState({
					btnBg: "red",
					btnColor: "#fff",
				})
			}else{
				this.setState({
					btnBg: "#e1e1e1",
					btnColor: "#525252",
				})

			}
		}
		this.setState({
			value,
		})
	}
	//用户输入密码
	onPswdChange = (pwd) => {
		if(this.state.value && pwd) {
			this.setState({
				btnBg: "red",
				btnColor: "#fff",
			})
		}else {
			this.setState({
				btnBg: "#e1e1e1",
				btnColor: "#525252",
			})
		}
		this.setState({
			pwd,
		})
	}
	//提交表单
	onSubmit() {
		const {value, pwd} = this.state;
		const {navigate} = this.props.navigation;
		Keyboard.dismiss();
		if(value && pwd) {
			User.getLogin(value, pwd).then(() => {
				if(User.list.isFetching) {
					navigate("PersonalCenter");
				}
			})
		}else{
			Toast.info("手机号或者密码不能为空");
		}
	}
	render() {
		const {navigate} = this.props.navigation;
		return(
			<View style={styles.form}>
				<List>
					<InputItem
						type="number"
						placeholder="请输入手机号码"
						error={this.state.hasError}
						onErrorClick={this.onErrorClick}
						onChange={this.onPhoneChange}
						value={this.state.value}
					>
					手机号码
					</InputItem>
					<InputItem
						type="password"
						placeholder="请输入密码"
						value={this.state.pwd}
						onChange={this.onPswdChange}

					>
					密 码
					</InputItem>
				</List>
				<Button 
					style={[styles.btn, {backgroundColor: this.state.btnBg}]}
					onClick={this.onSubmit.bind(this)}
				>
					<Text style={{color: this.state.btnColor}}>登录</Text>
				</Button>
				<View style={styles.linkTo}>
					<Text style={styles.linkText} onPress={() => navigate("register")}>
						还未注册？立即注册
					</Text>
					<Text style={styles.linkText}>
						修改密码
					</Text>
				</View>
			</View>
		);
	}
}

const styles = StyleSheet.create({
	form: {
		marginTop: 30,
		padding: 10,
	},
	linkTo: {
		flexDirection: "row",
		justifyContent: "space-between",
		marginTop: 3,
		marginBottom: 20,
	},
	linkText: {
		color: "#FA381A",
	},
	btn: {
		marginTop: 20,
		marginBottom: 3,
	}
})

export default Login;